<script setup lang="ts">
import {
  getPatientList,
  addPatient,
  updatePatient,
  deletePatient
} from '@/service/user'
import { onMounted, ref, computed } from 'vue'
import type { PatientList, Patient } from '@/types/user'
import { nameRules, idCardRules } from '@/utils/rules'
import { IdCardFilter } from '@/utils/tools'
import {
  showSuccessToast,
  type FormInstance,
  showConfirmDialog,
  showFailToast
} from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores'

const store = useConsultStore()
const router = useRouter()

// 患者信息
const patientList = ref<PatientList>([])
const LoadList = async () => {
  const res = await getPatientList()
  patientList.value = res.data
  // 默认选中的患者
  if (isChange.value && patientList.value.length) {
    const defaultPatient = patientList.value.find(
      (item) => item.defaultFlag === 1
    )
    if (defaultPatient) {
      patientId.value = defaultPatient.id
    } else {
      patientId.value = patientList.value[0].id
    }
  }
}

// 患者按钮
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
const gender = ref(1)
onMounted(() => {
  LoadList()
})

// 打开侧滑重置表单
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}
// 表单信息
// 不太理解这里结合下面的解构的写法是为什么？
const patient = ref<Patient>({
  ...initPatient
})
// 默认值给到checkbox -> 它需要的是布尔值
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },
  set(value) {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

// 使用van-pop 实现侧滑表单
const show = ref(false)
const showPopup = (item?: Patient) => {
  show.value = true
  if (item?.id) {
    const { name, id, idCard, defaultFlag, gender } = item
    patient.value = { name, id, idCard, defaultFlag, gender }
  } else {
    patient.value = { ...initPatient }
  }
}

// 添加患者于编辑患者 表单校验
const form = ref<FormInstance>()
const onSubmit = async () => {
  await form.value?.validate()
  // 校验通过
  // +'1' => 能够把字符串变为数字1  性别判断
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '性别和身份证中的不一致\n是否确认提交？'
    })
  }
  if (patient.value.id) {
    // 编辑患者接口
    await updatePatient(patient.value)
    // 编辑成功
    showSuccessToast('编辑成功')
  } else {
    // 添加患者接口
    await addPatient(patient.value)
    // 添加成功
    showSuccessToast('添加成功')
  }
  // 关闭弹窗
  show.value = false
  // 重新获取数据
  LoadList()
}

// 删除患者
const removePatient = async () => {
  if (patient.value.id) {
    try {
      await showConfirmDialog({
        title: '温馨提示',
        message: `您确认要删除${patient.value.name}患者吗？`
      })
      await deletePatient(patient.value?.id)
      show.value = false
      LoadList()
    } catch (error) {
      console.log(error)
    }
  }
}

// 是否选择患者
const route = useRoute()
const isChange = computed(() => {
  return route.query.isChange === '1'
})

// 病情描述-选择患者
const patientId = ref<string>()
const selectPatient = (item: Patient) => {
  patientId.value = item.id
}

// 下一步
const next = () => {
  // 判断是否选择了病患
  if (!patientId.value) return showFailToast('请选择病患')
  // 存储病患信息
  store.setPatient(patientId.value)
  // 路由跳转
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <!-- 头部 -->
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>

    <!-- 档案列表 -->
    <div class="patient-list" v-if="patientList">
      <div
        class="patient-item"
        v-for="item in patientList"
        :key="item.id"
        :class="{ selected: patientId === item.id }"
        @click="selectPatient(item)"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{ IdCardFilter(item.idCard) }}</span>
          <span class="sex">{{ item.genderValue }}</span>
          <span class="age"> {{ item.age }} 岁</span>
        </div>
        <div class="icon">
          <cp-icon name="user-edit" @click="showPopup(item)"></cp-icon>
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div
        class="patient-add"
        v-if="patientList.length < 6"
        @click="showPopup()"
      >
        <cp-icon name="user-add"></cp-icon>
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可以添加6人</div>
      <!-- <cp-radio-button
        :options="options"
        :modelValue="gender"
        @update:modelValue="gender = $event"
      ></cp-radio-button> -->
      <cp-radio-button :options="options" v-model="gender"></cp-radio-button>
    </div>

    <!-- 侧边栏 -->
    <!-- 使用v-model -->
    <van-popup v-model:show="show" position="right">
      <!-- 头部 -->
      <cp-nav-bar
        :back="
          () => {
            show = false
          }
        "
        :title="patient.id ? '编辑患者' : '新增患者'"
        right-text="保存"
      >
      </cp-nav-bar>

      <!-- 表单绘制 -->
      <!-- 
        autoComplete - 是否自动补全 
        ref - 获取dom元素
      -->
      <van-form autoComplete="off" ref="form" @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            label="真实姓名"
            placeholder="真实姓名"
            v-model="patient.name"
            :rules="nameRules"
          />
          <van-field
            label="身份证号"
            placeholder="身份证号"
            v-model="patient.idCard"
            :rules="idCardRules"
          />
          <van-field label="性别" class="pb4">
            <!-- #input 自定义输入框 使用后 与输入框相关的属性和事件失效 -->
            <template #input>
              <!-- modelValue是可选的参数 -->
              <cp-radio-button
                :options="options"
                v-model="patient.gender"
              ></cp-radio-button>
            </template>
          </van-field>
          <van-field label="默认就诊人" class="pb4">
            <template #input>
              <van-checkbox v-model="defaultFlag"> </van-checkbox>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
      <van-action-bar>
        <van-action-bar-button @click="removePatient"
          >删除患者</van-action-bar-button
        >
      </van-action-bar>
    </van-popup>

    <!-- 不使用v-model -->
    <!-- <van-popup :show="show" @update:show="show = $event" position="right">
      <cp-nav-bar title="添加患者" right-text="保存"> 12312312 </cp-nav-bar>
    </van-popup> -->
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
    }
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-list {
  padding: 15px;
}
.patient-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border: 1px solid var(--cp-bg);
  border-radius: 10px;
  margin-bottom: 15px;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      margin-right: 20px;
      line-height: 30px;
      color: var(--cp-tip);
      &.name {
        width: 80px;
        font-size: 16px;
        color: var(--cp-text1);
        margin-right: 0;
      }
      &.id {
        width: 180px;
        color: var(--cp-text2);
      }
    }
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    line-height: 16px;
    text-align: center;
    background-color: var(--cp-primary);
    color: white;
  }
  .icon {
    color: var(--cp-tag);
    font-weight: 700;
  }
}

.patient-add {
  height: 45px;
  padding: 15px 0;
  background-color: var(--cp-bg);
  border-radius: 10px;
  color: var(--cp-primary);
  text-align: center;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}

// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
.selected {
  border: 1px solid var(--cp-primary);
}
</style>
